import akshare as ak

# fund_open_fund_rank_em_df = ak.fund_open_fund_rank_em(symbol="全部")
# print(fund_open_fund_rank_em_df)

import streamlit as st
import pandas as pd

@st.cache_data(ttl=300, show_spinner=False)
def _load_fund_rank(symbol: str = "全部"):
    try:
        return ak.fund_open_fund_rank_em(symbol=symbol)
    except Exception as err:
        return err


def main():
    # 页面配置
    st.set_page_config(page_title="基金排行", layout="wide")
    st.title("基金排行展示")

    # 数据获取
    with st.spinner("正在加载基金排行数据..."):
        data = _load_fund_rank(symbol="全部")

    if isinstance(data, Exception):
        st.error(f"获取数据失败：{data}")
        st.stop()

    fund_open_fund_rank_em_df = data

    if fund_open_fund_rank_em_df is None or fund_open_fund_rank_em_df.empty:
        st.warning("未获取到基金排行数据。")
        st.stop()

    # 精简列并格式化，避免页面显示过于杂乱
    preferred_columns = [
        "基金代码",
        "基金简称",
        "日期",
        "单位净值",
        "累计净值",
        "日增长率",
        "近1周",
        "近1月",
        "近3月",
        "近6月",
        "近1年",
    ]
    present_columns = [c for c in preferred_columns if c in fund_open_fund_rank_em_df.columns]
    df = fund_open_fund_rank_em_df[present_columns].copy() if present_columns else fund_open_fund_rank_em_df.copy()

    # 关键字过滤
    with st.sidebar:
        st.header("筛选")
        keyword = st.text_input("按基金简称关键字过滤", "")
        default_sort_col = "日增长率" if "日增长率" in df.columns else df.columns[0]
        sort_col = st.selectbox("排序列", options=list(df.columns), index=list(df.columns).index(default_sort_col))
        sort_desc = st.toggle("降序", value=True)
        compact = st.toggle("紧凑模式", value=True)

    if keyword:
        if "基金简称" in df.columns:
            df = df[df["基金简称"].astype(str).str.contains(keyword, case=False, na=False)]

    # 数值/百分比格式化
    percent_like_cols = [c for c in df.columns if ("增长率" in c) or c.startswith("近")]
    number_like_cols = [c for c in df.columns if c in {"单位净值", "累计净值"}]

    for c in number_like_cols:
        if c in df.columns:
            df[c] = pd.to_numeric(df[c], errors="coerce")
    for c in percent_like_cols:
        if c in df.columns:
            # 兼容可能自带%的情况
            series = df[c].astype(str).str.replace("%", "", regex=False)
            df[c] = pd.to_numeric(series, errors="coerce") / 100.0

    # 排序
    if sort_col in df.columns:
        df = df.sort_values(by=sort_col, ascending=not sort_desc, na_position="last")

    # 列配置：美化展示
    column_config = {}
    for c in number_like_cols:
        if c in df.columns:
            column_config[c] = st.column_config.NumberColumn(c, format="%.4f")
    for c in percent_like_cols:
        if c in df.columns:
            column_config[c] = st.column_config.NumberColumn(c, format="%.2%")

    height = 520 if compact else 680

    st.success("数据加载完成 ✅")

    # 展示表格
    st.dataframe(
        df,
        use_container_width=True,
        height=height,
        column_config=column_config if column_config else None,
        hide_index=True,
    )

    # 下载功能
    # 百分比列恢复为字符串%以便下载查看
    df_download = df.copy()
    for c in percent_like_cols:
        if c in df_download.columns:
            df_download[c] = (df_download[c] * 100).map(lambda x: f"{x:.2f}%" if pd.notna(x) else "")
    csv = df_download.to_csv(index=False).encode("utf-8-sig")
    st.download_button(
        label="📥 下载基金排行CSV",
        data=csv,
        file_name="fund_rank.csv",
        mime="text/csv",
    )

if __name__ == "__main__":
    main()